"use strict";
$(function () {
    initialPage();
    getGrid();
});

function initialPage() {
    $(window).resize(function () {
        TreeGrid.table.resetHeight({height: $(window).height() - 100});
    });
}

function getGrid() {
    var colunms = TreeGrid.initColumn();
    var table = new TreeTable(TreeGrid.id, '../org/company/list', colunms);
    table.setExpandColumn(2);
    table.setIdField("deptId");
    table.setCodeField("deptId");
    table.setParentCodeField("parentId");
    table.setExpandAll(true);
    table.setHeight($(window).height() - 100);
    table.init();
    TreeGrid.table = table;
}

var TreeGrid = {
    id: "orgCompanyGrid",
    table: null,
    layerIndex: -1
};


/**
 * 初始化表格的列
 */
TreeGrid.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: 'ID', field: 'deptId', visible: false, align: 'center', valign: 'middle', width: '80px'},
        {title: '名称', field: 'name', align: 'center', valign: 'middle', sortable: true, width: '180px'},
        {title: '类型', field: 'type', align: 'center', valign: 'middle', sortable: true, width: '100px',
        	formatter: function (item) {
	            if (item.type === '1') {
	                return '<span class="label label-success">公司</span>';
	            }
	            if (item.type === '2') {
	                return '<span class="label label-warning">大区</span>';
	            }
	        }
        },
        {title: '排序号', field: 'orderNum', align: 'center', valign: 'middle', sortable: true, width: '100px'}]
    return columns;
};

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};
var ztree;

var vm = new Vue({
    el: '#orgCompany',
    data: {
        showList: true,
        title: null,
        uploadInfo: {},
		baseImgUrl: "",
        uploadLicenseList:[],
        uploadIdcardPositiveList:[],
        uploadIdcardReverseList:[],
        dept: {
            parentName: null,
            parentId: '01',
            orderNum: 0
        },
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        }
    },
    methods: {
        getDept: function () {
            //加载部门树
            Ajax.request({
                url: "../org/company/select",
                async: true,
                successCallback: function (r) {
                	r.deptList.push({"deptId":"0","name":"一级菜单"});
                    ztree = $.fn.zTree.init($("#orgCompanyTree"), setting, r.deptList);
                    var node = ztree.getNodeByParam("deptId", vm.dept.parentId);
                    if (node) {
                        ztree.selectNode(node);
                        vm.dept.parentName = node.name;
                    } else {
                        node = ztree.getNodeByParam("deptId", '0');
                        ztree.selectNode(node);
                        vm.dept.parentName = node.name;
                    }
                }
            });
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            var deptId = TreeGrid.table.getSelectedRow();
            var parentId = '0';
            if (deptId.length != 0) {
                parentId = deptId[0].id;
            }
            vm.dept = {parentName: null, parentId: parentId, orderNum: 0,license:'',idcardPositive:'',idcardReverse:'',type:'1'};
            vm.getDept();
            vm.getUploadFileToken();
        },
        update: function () {
            var deptId = getDeptId();
            if (deptId == null) {
                return;
            }
            Ajax.request({
                url: "../org/company/info/" + deptId,
                async: true,
                successCallback: function (r) {
                    vm.showList = false;
                    vm.title = "修改";
                    vm.dept = r.dept;
                    if(vm.dept.license){
                    	vm.uploadLicenseList.push({name:vm.dept.license.substr(vm.dept.license.lastIndexOf("/")),url:vm.dept.license});
                    }
                    if(vm.dept.idcardPositive){
                    	vm.uploadIdcardPositiveList.push({name:vm.dept.idcardPositive.substr(vm.dept.idcardPositive.lastIndexOf("/")),url:vm.dept.idcardPositive});
                    }
                    if(vm.dept.idcardReverse){
                    	vm.uploadIdcardReverseList.push({name:vm.dept.idcardReverse.substr(vm.dept.idcardReverse.lastIndexOf("/")),url:vm.dept.idcardReverse});
                    }
                    vm.getDept();
                }
            });
            vm.getUploadFileToken();
        },
		getUploadFileToken:function(){
			Ajax.request({
                url: "../sysUpload/getToken",
                async: true,
                successCallback: function (r) {
                    vm.uploadInfo.token=r.uptoken;
                    vm.uploadInfo.key="companyInfo"+(new Date().getTime());
                    vm.baseImgUrl=r.baseImgUrl;
                }
            });
		},
        del: function () {
            var deptId = getDeptId();
            if (!deptId) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../org/company/delete",
                    params: {"deptId": deptId},
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        saveOrUpdate: function (event) {
            var url = vm.dept.deptId == null ? "../org/company/save" : "../org/company/update";
            Ajax.request({
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.dept),
                type: 'POST',
                successCallback: function () {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        deptTree: function () {
            openWindow({
                title: "选择上级",
                area: ['300px', '450px'],
                content: jQuery("#orgCompanyLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级部门
                    vm.dept.parentId = node[0].deptId;
                    vm.dept.parentName = node[0].name;

                    layer.close(index);
                }
            });
        },
        reload: function () {
            vm.showList = true;
            TreeGrid.table.refresh();
        },
        handleView:function(file){
        	console.log("view:",file.url);
        	openWindow({
            	type: 2,
                title: "图片显示",
                area: ['80%', '60%'],
                content: [file.url],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                    layer.close(index);
                }
            });
        },
        handleRemove:function(type){
        	switch (type) {
				case "license":vm.uploadLicenseList=[];break;
				case "idcardPositive":vm.uploadIdcardPositiveList=[];break;
				case "idcardReverse":vm.uploadIdcardReverseList=[];break;
				default:break;
			}
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate();
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleSuccessLicense:function(res, file){
        	vm.uploadLicenseList.push({name:file.name,url:vm.baseImgUrl+res.key,status:'finished'});
        	vm.dept.license=vm.baseImgUrl+res.key;
        },
        handleSuccessIdcardPositive:function(res, file){
        	vm.uploadIdcardPositiveList.push({name:file.name,url:vm.baseImgUrl+res.key,status:'finished'});
        	vm.dept.idcardPositive=vm.baseImgUrl+res.key;
        },
        handleSuccessIdcardReverse:function(res, file){
        	vm.uploadIdcardReverseList.push({name:file.name,url:vm.baseImgUrl+res.key,status:'finished'});
        	vm.dept.idcardReverse=vm.baseImgUrl+res.key;
        },
        handleImgFormatError:function(file){
        	alert('图片格式错误！支持图片格式为:jpg,png,jpeg!');
        },
        handleImgMaxSize:function(file){
        	alert('图片最大大小为4M!');
        },
        handleLicenseImgBeforeUpload:function(){
        	var check = vm.uploadLicenseList.length < 1;
            if (!check) {
            	alert('首先删除原来的图片!');
            }
            return check;
        },
        handleIdcardPositiveImgBeforeUpload:function(){
        	var check = vm.uploadIdcardPositiveList.length < 1;
        	if (!check) {
        		alert('首先删除原来的图片!');
        	}
        	return check;
        },
        handleIdcardReverseImgBeforeUpload:function(){
        	var check = vm.uploadIdcardReverseList.length < 1;
        	if (!check) {
        		alert('首先删除原来的图片!');
        	}
        	return check;
        }
    }
});

function getDeptId() {
    var selected = $('#orgCompanyGrid').bootstrapTreeTable('getSelections');
    if (selected.length == 0) {
        iview.Message.error("请选择一条记录");
        return false;
    } else {
        return selected[0].id;
    }
}